import { createWebHashHistory, createRouter } from 'vue-router'

import admin from '@/layout/admin.vue'
import Login from '@/pages/login.vue'
import Index from '@/pages/index.vue'
import NotFound from '@/pages/notFound.vue'
import GoodList from '@/pages/goods/list.vue'
import categoryList from '@/pages/category/list.vue'

// const routes = [
//   {
//     path: '/',
//     component: admin,
//     children: [
//       {
//         path: '/',
//         component: Index,
//         meta: { title: '首页' },
//       },
//       {
//         path: '/goods/list',
//         component: GoodList,
//         meta: { title: '商品管理' },
//       },
//       {
//         path: '/category/list',
//         component: categoryList,
//         meta: { title: '分类列表' },
//       },
//     ],
//   },
//   { path: '/login', component: Login, meta: { title: '登录' } },
//   {
//     path: '/:pathMatch(.*)*',
//     name: 'NotFound',
//     component: NotFound,
//     meta: { title: '404' },
//   },
// ]
//默认路由  所有用户共享
const routes = [
  {
    path: '/',
    name: 'admin',
    component: admin,
  },
  {
    path: '/login',
    component: Login,
    meta: {
      title: '登录页',
    },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
  },
]
// 动态路由 用于匹配菜单  动态添加路由
const asyncRoutes = [
  {
    path: '/',
    name: '/',
    component: Index,
    meta: { title: '后台首页' },
  },
  {
    path: '/goods/list',
    name: '/goods/list',
    component: GoodList,
    meta: { title: '商品管理' },
  },
  {
    path: '/category/list',
    name: '/category/list',
    component: categoryList,
    meta: { title: '分类列表' },
  },
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes,
})
export function addRoutes(menus) {
  // 是否有新的路由
  let hasNewRoutes = false
  const findAndAddRoutesByMenus = (arr) => {
    arr.forEach((e) => {
      let item = asyncRoutes.find((o) => o.path == e.frontpath)
      if (item && !router.hasRoute(item.path)) {
        router.addRoute('admin', item)
        hasNewRoutes = true
      }
      if (e.child && e.child.length > 0) {
        findAndAddRoutesByMenus(e.child)
      }
    })
  }

  findAndAddRoutesByMenus(menus)

  return hasNewRoutes
}
